package com.jushu.storbox;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.Window;

import com.jushu.storbox.constant.ClientConfig;
import com.jushu.storbox.manager.ActivityTaskManager;
import com.jushu.storbox.service.CloudDriveService;
import com.jushu.storbox.util.LogUtil;
import com.jushu.storbox.util.PublicTools;

/**
 * PreparedActivity
 */
public class PreparedActivity extends Activity {

    private final static String LOG_TAG = "PreparedActivity";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        LogUtil.i(LOG_TAG, "onCreate()");
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        ActivityTaskManager.getInstance().putActivity(LOG_TAG,
                PreparedActivity.this);
        startCLoudDriveService();
        chooseActivity();
    }

    @Override
    protected void onDestroy() {
        LogUtil.i(LOG_TAG, "onDestroy()");
        super.onDestroy();
        ActivityTaskManager.getInstance().removeActivity(LOG_TAG);
    }

    private void startCLoudDriveService() {
        Intent cloudDriveService = new Intent(PreparedActivity.this, CloudDriveService.class);
        startService(cloudDriveService);
    }

    /**
     * PreparedActivity jump to activity
     */
    private void chooseActivity() {
        Intent intent = new Intent();
        if (versionIsChanged()) {
            intent.setClass(PreparedActivity.this, WelcomeActivity.class);
        } else {
            SharedPreferences settings = getSharedPreferences(
                    ClientConfig.settings, Context.MODE_APPEND);
            if (settings.getBoolean(ClientConfig.AUTOLOGIN, false) ) {
                if(PublicTools.isLoginSuccess(PreparedActivity.this)){
                    ShareDriveApplication.getInstance().setAuthorization(null);
                    intent.setClass(PreparedActivity.this, LoginWaitActivity.class);
                    intent.setAction("loginAuto");
                }else{
                    intent.setClass(PreparedActivity.this, LoginActivity.class);
                }
            } else {
                intent.setClass(PreparedActivity.this, LoginActivity.class);
            }
        }
        startActivity(intent);
        PreparedActivity.this.finish();
    }

    /**
     * @param versionCode
     * @return boolean
     */
    public boolean versionIsChanged() {
        SharedPreferences settings = getSharedPreferences(
                ClientConfig.settings, Context.MODE_APPEND);
        boolean isChange = false;
        int code = settings.getInt("VERSIONCODE", 0);
        if (!(code == PublicTools.getVersionCode(PreparedActivity.this))) {
            isChange = true;
        }
        return isChange;
    }
}
